package cn.org.rookie.jeesdp.core.utils;

import javax.crypto.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random;

/**
 * AES加密工具类，提供字符串和字节数组的加密、解密功能
 *
 * @author LHT
 * &#064;date  2022-06-28 21:23
 */
public class AESUtils {

    /**
     * AES加密算法配置：ECB模式，PKCS5Padding填充
     */
    private static final String CIPHER = "AES/ECB/PKCS5Padding";

    /**
     * AES加密算法名称
     */
    private static final String AES = "AES";

    /**
     * 安全随机数生成器算法
     */
    private static final String SHA1PRNG = "SHA1PRNG";

    /**
     * 字符编码格式
     */
    private static final String UTF_8 = "UTF-8";

    /**
     * 随机数生成器
     */
    private static final Random RANDOM = new Random();

    /**
     * 随机字节长度，用于生成密钥
     */
    private static final int RANDOM_LENGTH = 4;

    /**
     * AES加密器
     */
    private static final Cipher cipher;

    /**
     * AES密钥生成器
     */
    private static final KeyGenerator generator;

    /**
     * AES密钥
     */
    private static SecretKey key;

    /*
      静态初始化块，初始化加密器和密钥生成器
     */
    static {
        try {
            cipher = Cipher.getInstance(CIPHER);
            generator = KeyGenerator.getInstance(AES);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException("初始化AES加密工具失败", e);
        }
    }

    /**
     * 加密字节数组
     *
     * @param source 需要加密的原始字节数组
     * @return 加密后的字节数组，前4字节为随机种子，后面为加密内容
     * @throws RuntimeException 当加密过程中出现错误时抛出
     */
    public static byte[] encrypt(byte[] source) {
        try {
            // 生成随机种子
            byte[] randomBytes = new byte[RANDOM_LENGTH];
            RANDOM.nextBytes(randomBytes);

            // 使用随机种子初始化安全随机数生成器
            SecureRandom secureRandom = SecureRandom.getInstance(SHA1PRNG);
            secureRandom.setSeed(randomBytes);

            // 生成密钥并初始化加密器
            generator.init(secureRandom);
            cipher.init(Cipher.ENCRYPT_MODE, generator.generateKey());

            // 执行加密
            byte[] cipherBytes = cipher.doFinal(source);

            // 将随机种子和加密内容合并
            byte[] result = new byte[randomBytes.length + cipherBytes.length];
            System.arraycopy(randomBytes, 0, result, 0, randomBytes.length);
            System.arraycopy(cipherBytes, 0, result, randomBytes.length, cipherBytes.length);

            return result;
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException e) {
            throw new RuntimeException("加密过程失败", e);
        }
    }

    /**
     * 解密字节数组
     *
     * @param source 需要解密的字节数组，前4字节为随机种子，后面为加密内容
     * @return 解密后的原始字节数组
     * @throws RuntimeException 当解密过程中出现错误时抛出
     */
    public static byte[] decrypt(byte[] source) {
        try {
            // 提取随机种子和加密内容
            byte[] randomBytes = new byte[RANDOM_LENGTH];
            byte[] cipherBytes = new byte[source.length - randomBytes.length];
            System.arraycopy(source, 0, randomBytes, 0, randomBytes.length);
            System.arraycopy(source, randomBytes.length, cipherBytes, 0, cipherBytes.length);

            // 使用随机种子初始化安全随机数生成器
            SecureRandom secureRandom = SecureRandom.getInstance(SHA1PRNG);
            secureRandom.setSeed(randomBytes);

            // 生成密钥并初始化解密器
            generator.init(secureRandom);
            cipher.init(Cipher.DECRYPT_MODE, generator.generateKey());

            // 执行解密
            return cipher.doFinal(cipherBytes);
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException e) {
            throw new RuntimeException("解密过程失败", e);
        }
    }

    /**
     * 加密字符串
     *
     * @param source 需要加密的原始字符串
     * @return Base64编码的加密字符串
     * @throws RuntimeException 当加密过程中出现错误时抛出
     */
    public static String encrypt(String source) {
        return Base64.getEncoder().encodeToString(encrypt(source.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * 解密字符串
     *
     * @param source Base64编码的加密字符串
     * @return 解密后的原始字符串
     * @throws RuntimeException 当解密过程中出现错误时抛出
     */
    public static String decrypt(String source) {
        return new String(decrypt(Base64.getDecoder().decode(source)), StandardCharsets.UTF_8);
    }

    /**
     * 测试方法，用于验证加密解密功能
     *
     * @param args 命令行参数
     */
    static void main(String[] args) {
        String demo = encrypt("demo");
        System.out.println(demo);
        System.out.println(decrypt(demo));
        System.out.println(encrypt("admin"));
        System.out.println(encrypt("1acafec5029a4a20bb0a2455b1f12692"));
    }

}
